#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
@File    :   learn_ORM.py
@Time    :   2025/01/20 22:53:22
@Author  :   xiangyu Chen
@Version :   1.0
@Contact :   yu112yu@sina.com
@License :   (C)Copyright 2017-2018, Liugroup-NLPR-CASIA
@python_requires    :   None
@Desc    :   ORM 全称“Object Relational Mapping”
'''

# 首先来定义 Field 类，它负责保存数据库表的字段名和字段类型：


class Field(object):
    def __init__(self, name, column_type):
        self.name = name
        self.column_type = column_type

    def __str__(self):
        # 创建实例的类的名字，及实例的name属性
        return '<%s:%s>' % (self.__class__.__name__, self.name)


# 在 Field 的基础上，进一步定义各种类型的 Field，比如 StringField，IntegerField 等等：
class StringField(Field):
    def __init__(self, name):
        # 形式显式指定了子类名和实例，适用于需要明确指定调用的父类的情况。
        super(StringField, self).__init__(name, 'varchar(100)')


class IntegerField(Field):
    def __init__(self, name):

        super(IntegerField, self).__init__(name, 'bigint')

# 接下来，来定义 ModelMetaclass 类，它负责创建 Model 类：


class ModelMetaclass(type):
    def __new__(cls, name, bases, attrs):
        # 排除掉对 Model 类的特殊属性和方法的处理
        if name == 'Model':
            return type.__new__(cls, name, bases, attrs)
        print('Found model: %s' % name)
        mappings = dict()
        for k, v in attrs.items():
            if isinstance(v, Field):
                print('Found mapping: %s ==> %s' % (k, v))
                mappings[k] = v
        for k in mappings.keys():
            attrs.pop(k)
        attrs['__mappings__'] = mappings  # 保存属性和列的映射关系
        attrs['__table__'] = name  # 假设表名和类名一致
        return type.__new__(cls, name, bases, attrs)

# 最后，来定义基类 Model 类，并使用 ModelMetaclass 作为 metaclass：


class Model(dict, metaclass=ModelMetaclass):

    def __init__(self, **kwargs):
        super(Model, self).__init__(**kwargs)

    def __getattr__(self, key):
        try:
            return self[key]
        except KeyError:
            raise AttributeError(r"'Model' object has no attribute 's%" % key)

    def __setattr__(self, key, value):
        self[key] = value

    def save(self):
        fields = []
        params = []
        args = []
        for k, v in self.__mappings__.items():
            fields.append(v.name)
            params.append('?')
            args.append(getattr(self, k, None))

        sql = 'insert into %s (%s) values (%s)' % (
            self.__table__, ','.join(fields), ','.join(params))
        print('SQL: %s' % sql)
        print('ARGS: %s' % str(args))


class User(Model):     # 定义类的属性到列的映射：
    id = IntegerField('id')
    name = StringField('username')
    email = StringField('email')
    password = StringField('password')



if __name__ == '__main__':
    u = User(id=12345, name='Michael', email='test@orm.org', password='my-pwd')
    u.save()
